﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Data.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Dimok;
using Dimok.Web.UI;
using Data;
public partial class Controls_Admin_ProfilesManager : System.Web.UI.UserControl {
	protected void Page_Load(object sender, EventArgs e) { }
	public static class ProfileFilterDataSource {
		static ProfileCommon Profile(string UserName) { return new ProfileCommon().GetProfile(UserName); }
		public static DataView SelectEx(string Username) {
			return Profile(Username).Filters.Filter.DefaultView;
		}
		public static void DeleteEx(string UserName, string Name,Control control) {
			ProfileCommon p = Profile(UserName);
			GridFilterDS dsFilters = p.Filters;
			dsFilters.Filter.FindByNamePageType(Name,PageBase.FilterPageType(control)).Delete();
			dsFilters.AcceptChanges();
			p.Save();
		}
	}

	void UpdateProfileSchema() {
		//foreach (ProfileInfo pi in ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All)) {
		//  ProfileCommon profile = new ProfileCommon().GetProfile(pi.UserName);
		//  GridFilterDS dsFrom = profile.Filters;
		//  GridFilterDS dsTo = new GridFilterDS();
		//  if (dsFrom.Filter.PrimaryKey.Length != dsTo.Filter.PrimaryKey.Length) {
		//    dsFrom.Relations.Clear();
		//    dsFrom.FilterGroups.ParentRelations.Clear();
		//    dsFrom.FilterGroups.ChildRelations.Clear();
		//    dsFrom.Filter.ParentRelations.Clear();
		//    dsFrom.Filter.ChildRelations.Clear();
		//    //dsFrom.Filter.Constraints.Clear();
		//    //List<DataColumn> dc = new List<DataColumn>( dsFrom.Filter.PrimaryKey);
		//    //dc.Add(dsFrom.Filter.Columns.Add(dsTo.Filter.PrimaryKey[1].ColumnName, dsTo.Filter.PrimaryKey[1].DataType));
		//    //dsFrom.Filter.ChildRelations.Clear();
		//    //dsFrom.Filter.PrimaryKey = dc.ToArray();
		//  }
		//  DataSet dsNS = new DataSet();
		//  dsNS.ReadXml(new StringReader(dsFrom.GetXml()));
		//  dsTo.Merge(dsNS);
		//  if (((UniqueConstraint)dsTo.Filter.Constraints[0]).Columns.Length == 1)
		//    dsTo.Filter.Constraints.RemoveAt(0);
		//  profile.Filters = dsTo;
		//  PageSettingsDS dsPSFrom = profile.PageSettings;
		//  PageSettingsDS dsPSTo = new PageSettingsDS();
		//  try {
		//    dsPSTo.ReadXml(new StringReader(dsPSFrom.GetXml()));
		//  } catch (Exception exc) {
		//    dsPSFrom.Clear();
		//    dsPSTo.ReadXml(new StringReader(dsPSFrom.GetXml()));
		//  }
		//  //dsPSFrom.Page.Columns.Remove(dsPSFrom.Page.FontSizeColumn);
		//  //dsPSTo.Merge(dsPSFrom);
		//  profile.PageSettings = dsPSTo;
		//  ///Might need it. Don't erase
		//  /*profile.Filters.Filter.PrimaryKey = new DataColumn[] { profile.Filters.Filter.NameColumn };*/
		//  profile.Save();
		//  //GridFilterDS.FilterDataTable dtFrom = profile.Filters.Filter;
		//  //GridFilterDS.FilterDataTable dtTo = new GridFilterDS.FilterDataTable();
		//  //dtTo.Merge(dtFrom);
		//  //profile.Filters.Tables.Remove(dtFrom);
		//  //profile.Filters.Tables.Add(dtTo);
		//  //profile.Save();
		//  profile = new ProfileCommon().GetProfile(pi.UserName);
		//  foreach (GridFilterDS.FilterRow rowFIlter in profile.Filters.Filter)
		//    foreach (DataColumn col in profile.Filters.Filter.Columns)
		//      rowFIlter[col] = rowFIlter[col].ToString().Trim();
		//  profile.Filters.AcceptChanges();
		//  foreach (PageSettingsDS.PageRow rowPage in profile.PageSettings.Page)
		//    foreach (DataColumn col in profile.PageSettings.Page.Columns)
		//      try { rowPage[col] = rowPage[col]; } catch { rowPage[col] = col.DefaultValue; }
		//  profile.Filters.AcceptChanges();
		//  profile.Save();
		//}
	}

	protected override void OnInit(EventArgs e) {
		base.OnInit(e);
		grvFilters.RowCommand += new GridViewCommandEventHandler(grvFilters_RowCommand);
		dsFilters.TypeName = typeof(ProfileFilterDataSource).AssemblyQualifiedName;
		btnNewProfile.Click += new EventHandler(btnNewProfile_Click);
		btnRefreshSchema.Click += new EventHandler(btnRefreshSchema_Click);
		btnCopyToUserSettings.Click += new EventHandler(btnCopyToUserSettings_Click);
	}

	void btnCopyToUserSettings_Click(object sender, EventArgs e) {
		//foreach (ProfileInfo pi in ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All)) {
		//  ProfileCommon profile = new ProfileCommon().GetProfile(pi.UserName);
		//  foreach (PageSettingsDS.PageRow rowPage in profile.PageSettings.Page) {
		//    var page = profile.UserSettings.Pages.EnsureValue(rowPage.Name);
		//    #region Position
		//    page.Position.X = rowPage.Left;
		//    page.Position.Y = rowPage.Top;
		//    page.Size.Width = rowPage.Width;
		//    page.Size.Height = rowPage.Height;
		//    #endregion
		//    #region Grid
		//    foreach (var rowGrid in rowPage.GetGridViewRows()) {
		//      var grid = page.Grids.EnsureValue(rowGrid.ControlID);
		//      grid.Columns = rowGrid.Columns;
		//      grid.Filter = rowGrid.Filter;
		//      grid.ActiveRowKey = rowGrid.ActiveRowKey;
		//      foreach (var rowReport in rowGrid.GetReportRows()) {
		//        var report = grid.Reports.EnsureValue(rowReport.ReportName);
		//        report.FilterLinq = rowReport.FilterLinq;
		//        report.Columns = rowReport.Columns;
		//        report.DetailViewXYWH = rowReport.DetailViewXYWH;
		//        report.IsShared = rowReport.IsShared;
		//        foreach (var rowFilter in rowReport.GetFilterExpressionRows()) {
		//          var filter = report.Filters.EnsureValue(rowFilter.ColumnUniqueName);
		//          filter.FieldName = rowFilter.FieldName;
		//          filter.FieldValue = rowFilter.FieldValue;
		//          filter.FilterFunction = rowFilter.FilterFunction;
		//          filter.DataTypeName = rowFilter.DataTypeName;
		//        }
		//        foreach (var rowDock in rowReport.GetDockRows())
		//          report.Docks.EnsureValue(rowDock.Name).Children = rowDock.Children;
		//        foreach (var rowSort in rowReport.GetSortExpressionsRows())
		//          report.Sorts.EnsureValue(rowSort.FieldName).Order = rowSort.SortOrder;
		//        foreach (var rowDetail in rowReport.GetDetailColumnRows())
		//          report.Details.EnsureValue(rowDetail.ColumnName).ColumnPosition = rowDetail.ColumnPosition;
		//      }
		//    }
		//    #endregion
		//  }
		//  profile.Save();
		//}
	}

	protected void grvPFG_RowInserting(object sender, GridViewInsertEventArgs e) {
		Data.DataSources.ProfileFilterGroupsDataSource.InsertEx(grvProfiles.SelectedValue+"", grvFilters.SelectedValues["Name"] + "", e.InsertingValues["GroupName"] + "",this);
		e.Cancel = true;
		((GridViewEx)sender).RequiresDataBinding = true;
	}

	void btnRefreshSchema_Click(object sender, EventArgs e) {
		UpdateProfileSchema();
	}

	protected void grvFilters_RowCommand(object sender, GridViewCommandEventArgs e) {
		if (e.CommandName != "Copy") return;
		string userTo = ((DropDownList)((GridView)(e.CommandSource)).Rows[int.Parse(e.CommandArgument + "")].FindControl("ddlUserTo")).SelectedValue + "";
		if (userTo == "") throw new Exception("Must select User Profile.");
		userTo = Dimok.User.UserObject.CurrentUserDomain + "\\" + userTo;
		string userFrom = grvProfiles.SelectedValue + "";
		string filterName = ((GridView)e.CommandSource).DataKeys[int.Parse(e.CommandArgument + "")].Value + "";
		if (userTo.ToLower() == userFrom.ToLower()) throw new Exception("Must select different User Profile.");
		Data.DataSources.ProfileFiltersDataSource.Copy(userFrom, userTo, filterName,this);
		grvProfiles.RequiresDataBinding = true;
		//if( rowTo == null )filterFrom.AddFilterRow(rowFrom.
	}

	protected void btnNewProfile_Click(object sender, EventArgs e) {
		string userName =
			(tbNewUser.Text.StartsWith("\\") ? Dimok.User.UserObject.CurrentUserDomain : "") + Lib.GetUserName(tbNewUser.Text);
		Data.DataSources.ProfilesDataSource.Insert(userName);
		grvProfiles.RequiresDataBinding = true;
	}
}
